﻿using Microsoft.EntityFrameworkCore;

namespace Tpl.Ef.Pe
{
    public static class ModelBuilderExt
    {
        public static void AdjustPeDefaultAction(this ModelBuilder modelBuilder)
        {
            foreach (var item in modelBuilder.Model
               .GetEntityTypes())
            {
                item.SetTableName(item.GetTableName()?.ToLower());
            }

            foreach (var item in modelBuilder.Model
                .GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Select(p => new
                {
                    p.ClrType,
                    p.Name,
                    Pb = modelBuilder.Entity(p.DeclaringEntityType.ClrType).Property(p.Name),
                    MaxLength = p.GetMaxLength()
                }))
            {
                item.Pb.HasColumnName(item.Name.ToLower());

                // DateTime设置为time without time zone，否则其辉
                if (item.ClrType.Equals(typeof(DateTime)) || item.ClrType.Equals(typeof(DateTime?)))
                {
                    item.Pb.HasColumnType("timestamp without time zone");
                }
                else if (item.ClrType == typeof(string) && item.MaxLength == null)
                {
                    item.Pb.HasMaxLength(200);
                }
            }
        }
    }
}